<template>
  <div class="serivePage">
    <!-- 搜索 -->
    <div class="formSearch">
      <el-form>
        <el-form-item>
          <el-button v-if="authState == 2" type="success" @click="add">添加</el-button>
          <el-button v-if="authState == 1" type="success" @click="goAuthPageUrl">去授权</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="tableBox">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
        tooltip-effect="dark"
        style="width: 100%"
        class="dataTable"
      >
        <el-table-column prop="kfId" label="客服id" />
        <el-table-column prop="name" label="客服名称" />
        <el-table-column width="200" label="客服头像">
          <template #default="scope">
            <img
              style="width: 60px; height: 60px"
              :src="scope.row.headImg"
              alt=""
            />
          </template>
        </el-table-column>
        <el-table-column prop="url" label="客服链接" />
        <!-- <el-table-column prop="name" label="接待人数量" /> -->
        <el-table-column label="操作" show-overflow-tooltip>
          <template #default="scope">
            <div class="btnList">
              <el-button type="primary" link @click="edit(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="del(scope.row)">删除</el-button>
              <el-button type="primary" link @click="reception(scope.row)">接待人员管理</el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <div>
            {{ authState == 1 ? '暂未授权' : '暂无数据' }}
          </div>
        </template>
      </el-table>
    </div>

    <!-- *************对话框开始************* -->
    <el-dialog
      v-model="addFormDialog"
      :title="userState ? '新增客服' : '修改客服'"
      width="30%"
      center
      :close-on-click-modal="false"
    >
      <!-- 新增用户 -->
      <div>
        <el-form
          ref="formRef"
          :model="addForm"
          label-width="80px"
          :rules="userRules"
        >
          <el-form-item label="客服头像" prop="headImg">
            <!-- 上传图片 -->
            <div class="uploadWidth">
              <el-upload
                class="avatar-uploader"
                list-type="picture-card"
                :headers="headers"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handlePictureCardPreview"
              >
                <img v-if="headImg" :src="headImg" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="客服名称" prop="name">
            <el-input
              v-model="addForm.name"
              maxlength="20"
              placeholder="请输入客服名称"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFormDialog = false">取 消</el-button>
          <el-button type="primary" @click="addForm_enter(formRef)">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 接待人员管理 -->
    <el-drawer
      v-model="servicePage"
      title="接待人员管理"
      direction="rtl"
      class="serviceBox"
      size="60%"
    >
      <div class="userStyle">
        <el-form :inline="true">
          <el-form-item label="客服名称:">
            {{ serviceItem.name }}
          </el-form-item>
          <br />
          <el-form-item label="客服头像:">
            <img
              style="width: 60px; height: 60px"
              :src="serviceItem.headImg"
              alt=""
            />
          </el-form-item>
        </el-form>
        <el-form :inline="true" :model="ReceptionistForm">
          <el-form-item>
            <el-button type="success" plain @click="addReception">添加</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="userStyle">
        <el-table
          :data="serverData"
          border
          tooltip-effect="dark"
          style="width: 100%"
        >
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="state" label="接待状态">
            <template #default="scope">
              <span v-if="scope.row.state == 0">接待中</span>
              <span v-if="scope.row.state == 1">空闲</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" show-overflow-tooltip>
            <template #default="scope">
              <div class="btnList">
                <el-button type="danger" link @click="deleteReception(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
    <!-- 接待人弹窗 -->
    <el-dialog
      v-model="addServerShow"
      title="添加接待人"
      width="30%"
      center
      :close-on-click-modal="false"
    >
      <el-form :inline="true" :model="CustomerForm">
        <el-form-item class="inputWide" label="部门">
          <el-select
            v-model="CustomerName"
            placeholder="请选择"
            @change="selDepartment"
          >
            <el-option
              v-for="item in DepartmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          :data="CustomerData"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          max-height="400"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            prop="name"
            label="接待人昵称"
            show-overflow-tooltip
          />
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addServerShow = false">取 消</el-button>
          <el-button type="primary" @click="addReceptionSubmit()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  getAllList,
  delService,
  AddService,
  UpService,
  getAllReceptionist,
  getDepartmentList,
  getExternalUserList,
  saveReceptionist,
  deleteReceptionist,
  checkAuthState,
} from '@/api/server'
import { QYuploadUrl } from '@/utils/request'
import { getToken } from '@/utils/auth'

const uploadUrl = QYuploadUrl
const headers = {
  'Authorization-business': getToken(),
}
const formRef = ref(null)
const tableLoading = ref(false)
const formInline = ref({
  page: 1, // 当前页
  pageSize: 10, // 每页记录数
})
const tableData = ref([])
const userState = ref(1)
const addForm = ref({
  headImg: '',
  name: '',
})
const addFormDialog = ref(false)
const userRules = {
  name: [{ required: true, message: '请输入客服名称', trigger: 'blur' }],
  headImg: [{ required: true, message: '请上传头像', trigger: 'blur' }],
}
const servicePage = ref(false)
const serviceItem = ref({})
const serverData = ref([])
const addServerShow = ref(false)
const CustomerForm = ref({
  dates: [], // 成为客户时间数组
  lastTimes: [], // 上次消费时间
  phone: '', // 手机号
  page: 1, // 当前页
  pageSize: 10, // 每页数
  labelId: null,
})
const CustomerData = ref([])
const DepartmentList = ref([])
const CustomerName = ref('')
const ReceptionistForm = ref({
  name: '',
  state: null,
  openKfId: '',
  userIdList: [],
})
const headImg = ref('')
const authState = ref(null)
const authPageUrl = ref('')

onBeforeMount(() => {
  getAll()
  getAuthState()
})

// 方法集合
const getAuthState = () => {
  checkAuthState().then((res) => {
    // 授权状态 1-未授权 2-已授权 3-获取授权链接异常
    authState.value = res.data.state
    authPageUrl.value = res.data.authPageUrl
  })
}
const goAuthPageUrl = () => {
  if (authPageUrl.value) {
    window.open(authPageUrl.value)
  }
}
// 上传
const handlePictureCardPreview = (file) => {
  headImg.value = file.data.url
  addForm.value.headImg = file.data.mediaId
}
// 分页管理
const handleSizeChange = (val) => {
  formInline.value.pageSize = val
  getAll()
}
const handleCurrentChange = (val) => {
  formInline.value.page = val
  getAll()
}
// 新增用户
const add = () => {
  if (tableData.value.length < 10) {
    userState.value = 1
    addFormDialog.value = true
    addForm.value = {
      name: '', //
      headImg: '', //
      openKfId: '',
    }
    headImg.value = ''
  } else {
    ElMessage.warning('最多添加10个客服')
  }
}
// 编辑用户
const edit = (row) => {
  userState.value = 0
  addFormDialog.value = true
  const item = Object.assign({}, row)
  addForm.value = item
  headImg.value = addForm.value.headImg
}
// 确认新增用户
const addForm_enter = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (userState.value === 1) {
        AddService(addForm.value).then((res) => {
          if (res.code === '') {
            ElMessage({
              message: '新增成功',
              type: 'success',
            })
          }
          getAll()
          addFormDialog.value = false
        })
      } else {
        UpService(addForm.value).then((res) => {
          if (res.code === '') {
            ElMessage({
              message: '修改成功',
              type: 'success',
            })
          }
          getAll()
          addFormDialog.value = false
        })
      }
    } else {
      return false
    }
  })
}
// 删除用户
const del = async (row) => {
  ElMessageBox.confirm('此操作将永久删除该客服, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      delService({ openKfId: row.openKfId }).then((res) => {
        if (res.code === '') {
          ElMessage({
            type: 'success',
            message: '删除成功!',
          })
        }
        getAll()
      })
    })
    .catch(() => {})
}
// 初始化查询所有数据
const getAll = () => {
  tableLoading.value = true
  getAllList(formInline.value).then(res => {
    tableData.value = res.data
  }).finally(() => {
    tableLoading.value = false
  })
}
const reception = (row) => {
  serviceItem.value = row
  ReceptionistForm.value.openKfId = row.openKfId
  servicePage.value = true
  getReceptionist()
}
// 获取客服下的接待人员
const getReceptionist = () => {
  getAllReceptionist(ReceptionistForm.value).then((res) => {
    serverData.value = res.data
  })
}
const clear = () => {
  ReceptionistForm.value.name = ''
  ReceptionistForm.value.state = null
  getReceptionist()
}
// 添加接待人
const addReception = () => {
  addServerShow.value = true
  getDepartments()
}
// 获取客户列表数据
const getDepartments = async () => {
  const res = await getDepartmentList()
  DepartmentList.value = res.data
  const pid = DepartmentList.value[0].id
  CustomerName.value = DepartmentList.value[0].name
  getCustomerAll(pid)
}
const selDepartment = (e) => {
  getCustomerAll(e)
}
const getCustomerAll = (pid) => {
  getExternalUserList({ id: pid }).then((res) => {
    CustomerData.value = res.data
  })
}
// 选中接待人员
const handleSelectionChange = (val) => {
  ReceptionistForm.value.userIdList = val.map((el) => {
    return el.userId
  })
}
// 确认添加
const addReceptionSubmit = () => {
  saveReceptionist(ReceptionistForm.value).then((res) => {
    addServerShow.value = false
    ElMessage.success('添加成功')
    getReceptionist()
  })
}
// 删除接待员
const deleteReception = (row) => {
  ReceptionistForm.value = row
  ElMessageBox.confirm('此操作将永久删除该接待员, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteReceptionist(ReceptionistForm.value).then((res) => {
        if (res.code === '') {
          ElMessage({
            type: 'success',
            message: '删除成功!',
          })
        }
        getReceptionist()
      })
    })
    .catch(() => {})
}
</script>

<style lang="scss" scoped>
.serivePage {
  padding: 20px;
  margin-top: 20px;
  background-color: #FFFFFF;
}
.userStyle {
  padding: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #3A68F2;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 140px;
  line-height: 140px;
  text-align: center;
}
.avatar {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
